/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controler;

//import antlr.Version;
//import com.mysql.jdbc.Connection;
//import com.mysql.jdbc.Statement;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
 import java.io.*;
 import java.sql.*;
import java.util.*;
import java.text.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import karshafinsearch.parseDocument;
//    /**
//     * Processes requests for both HTTP
//     * <code>GET</code> and
//     * <code>POST</code> methods.
//     *
//     * @param request servlet request
//     * @param response servlet response
//     * @throws ServletException if a servlet-specific error occurs
//     * @throws IOException if an I/O error occurs
//     */
//    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
//            throws ServletException, IOException {
//        response.setContentType("text/html;charset=UTF-8");
//        PrintWriter out = response.getWriter();
//        try {
//            /*
//             * TODO output your page here. You may use following sample code.
//             */
//            out.println("<html>");
//            out.println("<head>");
//            out.println("<title>Servlet ControlerServelet</title>");            
//            out.println("</head>");
//            out.println("<body>");
//            out.println("<h1>Servlet ControlerServelet at " + request.getContextPath() + "</h1>");
//            out.println("</body>");
//            out.println("</html>");
//        } finally {            
//            out.close();
//        }
//    }
//
//    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
//    /**
//     * Handles the HTTP
//     * <code>GET</code> method.
//     *
//     * @param request servlet request
//     * @param response servlet response
//     * @throws ServletException if a servlet-specific error occurs
//     * @throws IOException if an I/O error occurs
//     */
//    @Override
//    protected void doGet(HttpServletRequest request, HttpServletResponse response)
//            throws ServletException, IOException {
//        processRequest(request, response);
//    }
//
//    /**
//     * Handles the HTTP
//     * <code>POST</code> method.
//     *
//     * @param request servlet request
//     * @param response servlet response
//     * @throws ServletException if a servlet-specific error occurs
//     * @throws IOException if an I/O error occurs
//     */
//    @Override
//    protected void doPost(HttpServletRequest request, HttpServletResponse response)
//            throws ServletException, IOException {
//        processRequest(request, response);
//    }
//
//    /**
//     * Returns a short description of the servlet.
//     *
//     * @return a String containing servlet description
//     */
//    @Override
//    public String getServletInfo() {
//        return "Short description";
//    }// </editor-fold>
/**
 *
 * @author lsf
 */
@WebServlet(name = "ControlerServelet",
loadOnStartup = 1 //        urlPatterns = {"/classify", "/markwithfibo", "/topkphrases", "/uploaddoc","/viewdocument","/viewphrase"}
)
public class ControlerServelet extends HttpServlet {
  //  private int byteRead;

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String userPath = request.getServletPath();

        // if category page is requested
        if (userPath.equals("/uploaddoc")) {
            // TODO: Implement category request
        } else if (userPath.equals("/login")) {
            userPath = "/karshalogin";
            // if cart page is requested
        } else if (userPath.equals("/topkphrases")) {
            // TODO: Implement cart page request
            //  userPath = "/cart";
            // if checkout page is requested
        } 
        
        else if (userPath.equals("/upload")) {
            


        }
           else if (userPath.equals("/viewPdf")) {
            

        }
        else if (userPath.equals("/queryOutput")) {
            // TODO: Implement cart page request
            //  userPath = "/cart";
            // if checkout page is requested
        } else if (userPath.equals("/docSimilarity")) {
            // TODO: Implement cart page request
            //  userPath = "/cart";
            // if checkout page is requested
        } else if (userPath.equals("/buildIndex")) {
            // TODO: Implement cart page request
            //  userPath = "/cart";
            // if checkout page is requested
        } else if (userPath.equals("/collection")) {
            // TODO: Implement cart page request
            //  userPath = "/cart";
            // if checkout page is requested
        } else if (userPath.equals("/selectdocument")) {
            // TODO: Implement cart page request
            //  userPath = "/cart";
            // if checkout page is requested
            List dataList = new ArrayList();
            List dataList1 = new ArrayList();
            dataList.add("credit card");
            dataList.add("Fixed Term Deposit");

            String str = (String) request.getParameter("SelecdocCatogary");
            dataList1.add(str);
            request.setAttribute("doccatogory", dataList);
            request.setAttribute(" selecteddocs", dataList1);

        } else if (userPath.equals("/classify")) {

            response.setContentType("text/html");

            List dataList = new ArrayList();
            List dataList1 = new ArrayList();
            PrintWriter pw = response.getWriter();

// String url = "jdbc:mysql://rss1.stratoslive.wso2.com/karshamarkuptool_karsha_opensource_lk";
////  //String url=null;  
//  String username = "root1_lQrhzZUK";
//    String password = "nbuser";


            String url = "jdbc:mysql://localhost:3306/karshamarkuptool";
//  //String url=null;  
            String username = "root";
            String password = "nbuser";
            BasicDataSource ds = new BasicDataSource();
            ds.setDriverClassName("com.mysql.jdbc.Driver");
            ds.setUrl(url);
            ds.setUsername(username);
            ds.setPassword(password);

            Connection connection = null;
            Connection connection1 = null;
            Statement stmt = null;
            Statement stmt1 = null;
            ResultSet rs = null;
            ResultSet rs1 = null;
            try {
                connection = ds.getConnection();
                //connection1 = ds.getConnection();
                stmt = connection.createStatement();
                // stmt1 = connection1.createStatement();
                rs = stmt.executeQuery("SELECT TaxonTerm from taxonomy");
                //   rs = stmt.executeQuery("SELECT PhraseContent,ScoreInDoc from phrase");

//rs1 = stmt1.executeQuery("SELECT PhraseContent,ScoreInDoc from phrase");
                while (rs.next()) {
                    //  int id = rs.getInt("id");
                    //  String name = rs.getString("name");
                    dataList.add(rs.getString(1));
                    //dataList.add(rs.getString(2));
                }



//        while (rs1.next()) {
//          //  int id = rs.getInt("id");
//            //  String name = rs.getString("name");
//     dataList1.add(rs1.getString(1));
//    dataList1.add(rs1.getString(2));
//       }

            } catch (SQLException e) {
                e.printStackTrace();
                pw.println(e.getMessage());
            } finally {
                try {
                    if (rs != null) {
                        rs.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                try {
                    if (stmt != null) {
                        stmt.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                try {
                    if (connection != null) {
                        connection.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            {
                try {
                    //connection = ds.getConnection();
                    connection1 = ds.getConnection();
                    //stmt = connection.createStatement();
                    stmt1 = connection1.createStatement();
                    // rs = stmt.executeQuery("SELECT TaxonTerm from taxonomy");
                    rs1 = stmt1.executeQuery("SELECT PhraseContent,ScoreInDoc from phrase");




                    while (rs1.next()) {
//          //  int id = rs.getInt("id");
//            //  String name = rs.getString("name");
                        dataList1.add(rs1.getString(1));
                        dataList1.add(rs1.getString(2));
                    }

                } catch (SQLException e) {
                    e.printStackTrace();
                    pw.println(e.getMessage());
                } finally {
                    try {
                        if (rs1 != null) {
                            rs1.close();
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    try {
                        if (stmt1 != null) {
                            stmt1.close();
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    try {
                        if (connection1 != null) {
                            connection1.close();
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }



            request.setAttribute("taxoterm", dataList);
            request.setAttribute("phrasescore", dataList1);

            // TODO: Implement checkout page request
            // if user switches language
        } else if (userPath.equals("/markwithfibo")) {

            response.setContentType("text/html");

            List dataList = new ArrayList();
            List dataList1 = new ArrayList();
            PrintWriter pw = response.getWriter();

// String url = "jdbc:mysql://rss1.stratoslive.wso2.com/karshamarkuptool_karsha_opensource_lk";
////  //String url=null;  
//  String username = "root1_lQrhzZUK";
//    String password = "nbuser";
            String url = "jdbc:mysql://localhost:3306/karshamarkuptool";
//  //String url=null;  
            String username = "root";
            String password = "nbuser";

            BasicDataSource ds = new BasicDataSource();
            ds.setDriverClassName("com.mysql.jdbc.Driver");
            ds.setUrl(url);
            ds.setUsername(username);
            ds.setPassword(password);

            Connection connection = null;
            Connection connection1 = null;
            Statement stmt = null;
            Statement stmt1 = null;
            ResultSet rs = null;
            ResultSet rs1 = null;
            try {
                connection = ds.getConnection();
                stmt = connection.createStatement();
                rs = stmt.executeQuery("SELECT FIBOTerm from fiboterm");

                while (rs.next()) {
                    //  int id = rs.getInt("id");
                    //  String name = rs.getString("name");
                    dataList.add(rs.getString(1));
                }

            } catch (SQLException e) {
                e.printStackTrace();
                pw.println(e.getMessage());
            } finally {
                try {
                    if (rs != null) {
                        rs.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                try {
                    if (stmt != null) {
                        stmt.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                try {
                    if (connection != null) {
                        connection.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            {
                try {
                    //connection = ds.getConnection();
                    connection1 = ds.getConnection();
                    //stmt = connection.createStatement();
                    stmt1 = connection1.createStatement();
                    // rs = stmt.executeQuery("SELECT TaxonTerm from taxonomy");
                    rs1 = stmt1.executeQuery("SELECT PhraseContent from phrase");




                    while (rs1.next()) {
//          //  int id = rs.getInt("id");
//            //  String name = rs.getString("name");
                        dataList1.add(rs1.getString(1));
                        // dataList1.add(rs1.getString(2));
                    }

                } catch (SQLException e) {
                    e.printStackTrace();
                    pw.println(e.getMessage());
                } finally {
                    try {
                        if (rs1 != null) {
                            rs1.close();
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    try {
                        if (stmt1 != null) {
                            stmt1.close();
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    try {
                        if (connection1 != null) {
                            connection1.close();
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }


            request.setAttribute("fiboterm", dataList);

            request.setAttribute("phrasescore", dataList1);
            // TODO: Implement language request
        } else if (userPath.equals("/viewdocument")) {
            // TODO: Implement language request
        } else if (userPath.equals("/viewphrase")) {
            // TODO: Implement language request
        }
        // use RequestDispatcher to forward request internally
        String url = "/WEB-INF/view" + userPath + ".jsp";

        try {
            request.getRequestDispatcher(url).forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String userPath = request.getServletPath();

        // if addToCart action is called
        if (userPath.equals("/classify")) {
            // TODO: Implement add product to cart action
            // if updateCart action is called
            
        } 
        else if (userPath.equals("/viewPdf")) {
            

      //  }




        } 
        
         else if (userPath.equals("/topkphrases")) {
            
              byte[] b = null;
            try {
                b = getBLOB("2");
            } catch (Exception ex) {
                Logger.getLogger(ControlerServelet.class.getName()).log(Level.SEVERE, null, ex);
            }
     
             
     ArrayList<String> sentenceList = new ArrayList<String>();
     parseDocument doc = new parseDocument();
        sentenceList=doc.pdfDocToSentence(b);
//       for(int i=0;i<sentenceList.size();i++){
// out.print(sentenceList.get(i));
//}
             
request.setAttribute("allphrases", sentenceList);
     
        } 
        
        else if (userPath.equals("/upload")) {
            

      //  }




        } else if (userPath.equals("/uploaddoc")) {
            

      //  }




        } else if (userPath.equals ( 
        "/purchase")) {
            // TODO: Implement purchase action

            userPath = "/confirmation";
    }
    // use RequestDispatcher to forward request internally
    String url = "/WEB-INF/view" + userPath + ".jsp";

    
        try {
            request.getRequestDispatcher(url).forward(request, response);
    }
    catch (Exception ex

    
        ) {
            ex.printStackTrace();
    }
}
    
    
    Connection getConnection() throws Exception {
          String driver = "com.mysql.jdbc.Driver";
          String url = "jdbc:mysql://localhost:3306/karshamarkuptool"; // replase dbname with actual name
          String username = "root";
          String password = "nbuser";
          Class.forName(driver);
          Connection conn = DriverManager.getConnection(url, username, password);
          return conn;
     }
  
     byte[] getBLOB(String _rptId) throws Exception {
          Connection conn = null;
          ResultSet rs = null;
          PreparedStatement pstmt = null;
          String query = "SELECT DocFile FROM Document b where DocID = ?";
          Blob blob = null;

          try {
               conn = getConnection();
               pstmt = conn.prepareStatement(query);
               pstmt.setString(1, _rptId); // assign the user requeested pdf id to the above prepared statement.
               rs = pstmt.executeQuery();
               rs.next();
               blob = rs.getBlob(1); // retrieve the blob stored as column PDF.
          } catch (Exception e) {
          } finally {
               rs.close();
               pstmt.close();
               conn.close();
          }
          if (blob != null) 
               return blob.getBytes((long)1, (int)blob.length());
          else
               return null;
     }
    
    
}
